<?php

namespace app\admin\controller;

use app\admin\model\Product;
use app\BaseController;
use app\dic\DicProduct;
use app\dic\DicPublic;
use app\dic\DicSite;
use think\App;
use think\facade\Db;

/**
 * @author xjw
 * @class:TaskProduct 定时任务=>产品操作
 * @method:product 拉取商品  45分钟执行
 * @method:deal_product 处理商品相关
 * @return  
 */


class Taskproduct extends BaseController
{

    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new Product();
    }





    //site.updatetime_product 升序  每次取一条站点更新
    public function product()
    {
        $type = input('type') ? input('type') : 1;
        $where = array();
        $result = array();
        $site_id = input('site_id');
        if (!empty($site_id)) {
            $where['id'] = $site_id;
        } else {
            $where[]  = ['id', '>=', 7];
        }
        if (!empty($type)) {
            $site = table('site')
                ->where('site_type', DicSite::$site_type_1)
                ->where('status', DicSite::$status_normal)
                ->where($where)
                ->order('updatetime_product asc')
                ->find();
            if ($site) {
                $this->deal_product($site, $type);
                return success('操作成功', $result);
            }
        }
    }

    /**
     * 后台自动获取数据
     * $type 2 实时拉取当下
     * $type 3 更新之前的
     */

    /**
     * deal_product 处理商品相关
     */
    public function deal_product($site, $type)
    {
        $url = $site['site_url'] . "/admin/api/2023-07/products.json";
        $limit = 50;
        if ($type == DicProduct::$type_3) {
            $limit = DicPublic::$task_limit_250;
            $product = table('product')
                ->where('site_id', $site['id'])
                ->order('ycreated_at asc')
                ->find();
            if ($product) {
                $created_at_max = $product['ycreated_at'];
            } else {
                date_default_timezone_set('Asia/Shanghai');
                $created_at_max1 = date('Y-m-d', strtotime("now"));
                $created_at_max2 = date('H:i:s', strtotime("now"));
                $created_at_max = $created_at_max1 . 'T' . $created_at_max2 . '-04:00';
            }
            $url = $url . '?created_at_max=' . $created_at_max;
        }
        if ($type == DicProduct::$type_2) {
            $limit = 50;
            $product = table('product')
                ->where('site_id', $site['id'])
                ->order('ycreated_at desc')
                ->find();
            if ($product) {
                $created_at_min = $product['ycreated_at'];
            } else {
                $created_at_min = '2021-07-01T00:00:00-04:00';
            }
            $url = $url . '?created_at_min=' . $created_at_min;
        }
        if ($type == DicProduct::$type_4) {
            $limit = 250;
            $product = table('product')
                ->where('site_id', $site['id'])
                ->order('yupdated_at desc')
                ->find();
            if ($product) {
                $updated_at_min = $product['yupdated_at'];
                $updated_at_mins = explode('T', $updated_at_min);
                $updated_at_mins[0] = date('Y-m-d', strtotime("$updated_at_mins[0]-1day"));
                $updated_at_min = $updated_at_mins[0] . 'T' . $updated_at_mins[1];
            } else {
                $updated_at_min = '2021-07-01T00:00:00-04:00';
            }
            $url = $url . '?updated_at_min=' . $updated_at_min;
        }
        $url = $url . '&limit=' . $limit;
        $data =  geturl($url, $site['apikey'], $site['apisecret']);
        if ($data) {
            $errors_time = array();
            $errors_time_errors = $data;
            $data = json_decode($data, true);
            if (!empty($data['errors'])) {
                $errors_time['errors'] = $errors_time_errors;
                $errors_time['updatetime_product'] = time();
                // $updatetime_product['status'] = DicSite::$status_unavailable;
                table('site')->where('id', $site['id'])->update($errors_time);
                return $site['site_url'] . '-' . $data['errors'];
            }
            $products = $data['products'];
            if (is_array($products) && !empty($products)) {
                // date_default_timezone_set('Asia/Shanghai');
                foreach ($products as  $v) {
                    $row = $this->model->where(['id' => $v['id']])->find();
                    //通过商品id取出品牌表中的值
                    $metafield =  table('brand')->where(['product_id' => $v['id']])->find();
                    $arr['id'] = $v['id'];
                    $arr['title'] = $v['title'];
                    $arr['body_html'] =  $v['body_html'];
                    $arr['vendor'] = $v['vendor'];
                    $arr['product_type'] = $v['product_type'];
                    $arr['ycreated_at'] = $v['created_at'];
                    $arr['yupdated_at'] = $v['updated_at'];
                    $arr['tags'] = $v['tags'];
                    $arr['status'] = $v['status'];
                    $arr['brand'] = !empty($metafield) ? $metafield['title'] : '';

                    if (!empty($v['images'])) {
                        $arr['images'] = $v['images'][0]['src'];
                    }

                    // 备份数据
                    if (!empty($v['images'])) {
                        $arr['images2'] = json_encode($v['images'], true);
                    }
                    if (!empty($v['options'])) {
                        $arr['options'] = json_encode($v['options'], true);
                    }

                    if (!empty($v['variants'])) {
                        table('productvariants')->where('product_id', $v['id'])->delete();
                        foreach ($v['variants'] as  $va) {
                            $vas['sku'] = $va['sku'];
                            $vas['price'] = $va['price'];
                            $vas['site_id'] = $site['id'];
                            $vas['product_id'] = $va['product_id'];
                            $vas['variants_id'] = $va['id'];
                            $vas['title'] = $va['title'];
                            $vas['option1'] = $va['option1'];
                            $vas['option2'] = $va['option2'];
                            $vas['option3'] = $va['option3'];
                            table('productvariants')->insert($vas);
                        }
                    }
                    $arr['site_id'] = $site['id'];
                    if ($row) {
                        $this->model->where(['id' => $row['id']])->update($arr);
                    } else {
                        $this->model->insert($arr);
                    }
                }
            }
        }
        $updatetime_product['updatetime_product'] = time();
        table('site')->where('id', $site['id'])->update($updatetime_product);
        return 1;
    }


    /**
     * 
     * 产品库sku处理
     */

    public function  demo_product_sku()
    {
        //查询产品库站点信息
        $site =  table('site')->where(['id' => 37])->find();
        $product = table('product')
            ->where('id', '>', 1)
            ->where('site_id', '37')
            ->order('updateordertime asc')
            ->find();
        if (!empty($product['id']) && isset($product['id'])) {
            $url = $site['site_url'] . DicProduct::$product_url . '/' . $product['id'] . '.json';
        } else {
            $url = '';
        }
        // halt($url);
        //取出产品库所有活跃的产品
        $api_active_products =  geturl($url, $site['apikey'], $site['apisecret']);
        if ($api_active_products) {
            $api_active_products = json_decode($api_active_products, true);
            if (!empty($api_active_products['errors'])) {
                $update['updateordertime'] = time();
                $product = table('product')
                    ->where('id', $product['id'])
                    ->update($update);
                return $api_active_products['errors'];
            }
            $active_products[] = $api_active_products['product'];
            if (is_array($active_products) && !empty($active_products)) {
                foreach ($active_products as  $product) {
                    $brand =  table('brand')->where(['product_id' => $product['id']])->find();
                    //获取商品的元字段信息
                    $metafield = $this->get_metafield_product_id($site, $product['id']);
                    if (!empty($brand)) {
                        //更新品牌
                        $brand_arr['title'] = isset($metafield['test2']) ?  $metafield['test2'] : (isset($metafield['test3']) ? $metafield['test3'] : '');
                        // 更新品牌
                        $brand_arr['update_time'] = date('Y-m-d H:i:s');
                        table('brand')->where(['product_id' => $product['id']])->update($brand_arr);
                    } else {
                        //插入品牌
                        if (!isset($metafield['test2'])) {
                            $metafield = isset($metafield['test3']) ? $metafield['test3'] : '';
                            //查询brand表 获取所有的品牌
                            $where[] = ['title', 'LIKE', "%{$metafield}%"];
                            $count = table('brand')->where($where)->count();
                            $count = $count == 0 ? ($count + 1) : $count;
                            $count = $count <= 9 ? ('0' . $count) : $count;
                            $title = $metafield . $count;
                        } else {
                            $title = $metafield['test2'];
                        }
                        $brand_arr['title'] = $title;
                        $brand_arr['product_id'] = $product['id'];
                        $brand_arr['create_time'] = date('Y-m-d H:i:s');
                        table('brand')->insert($brand_arr);
                    }
                    $update['updateordertime'] = time();
                    $update['brand'] = $brand_arr['title'];
                    $product = table('product')
                        ->where('id', $product['id'])
                        ->update($update);
                }
                return success('操作成功');
            }
        }
    }


    /**
     * 通过商品id获取元字段信息
     */

    public function  get_metafield_product_id($site, $product_id)
    {
        $url = $site['site_url'] . DicProduct::$product_url . '/' . $product_id . '/metafields.json';
        $metafield = geturl($url, $site['apikey'], $site['apisecret']);
        $metafield = json_decode($metafield, true);
        if (isset($metafield['metafields'])) {
            return  array_column($metafield['metafields'], 'value', 'key');
        }
        return [];
    }

    //更新sku总数
    public function update_sku_count()
    {
        $return = array();
        //每次取50
        $where[] = ['sku', 'LIKE', "%bra10%"];
        $data =  table('skuinventory')->order(['updatetime' => 'asc'])->where($where)->limit(100)->select()->toarray();
        foreach ($data as  $value) {
            $sql = "SELECT 
                sum(oq.quantity) as count
                FROM qu_order as o
                LEFT JOIN qu_order_quantity as oq ON o.id = oq.order_id
                LEFT JOIN qu_order_product as op ON op.product_id=oq.product_id
                LEFT JOIN qu_order_sku as os ON os.variants_id=oq.variant_id
                where o.financial_status = 'paid'
                AND o.fulfillment_status = 'unshipped'
                AND o.closed_at is null
                AND os.variants_id = " . $value['variants_id'];

            $count_sum = array_column(Db::query($sql), 'count');
            $count = $count_sum[0] == null ? 0 : (int)$count_sum[0];
            $sql1 = "SELECT 
            sum(oq.quantity) as count
            FROM qu_order as o
            LEFT JOIN qu_order_quantity as oq ON o.id = oq.order_id
            LEFT JOIN qu_order_product as op ON op.product_id=oq.product_id
            LEFT JOIN qu_order_sku as os ON os.variants_id=oq.variant_id
            where o.financial_status = 'partially_paid'
            AND o.fulfillment_status = 'unshipped'
            AND o.closed_at is null
            AND os.variants_id = " . $value['variants_id'];
            $count_sum1 = array_column(Db::query($sql1), 'count');
            $count1 = $count_sum1[0] == null ? 0 : (int)$count_sum1[0];

            $sql2 = "SELECT 
            sum(oq.quantity) as count
            FROM qu_order as o
            LEFT JOIN qu_order_quantity as oq ON o.id = oq.order_id
            LEFT JOIN qu_order_product as op ON op.product_id=oq.product_id
            LEFT JOIN qu_order_sku as os ON os.variants_id=oq.variant_id
            where o.financial_status = 'partially_refunded'
            AND o.fulfillment_status = 'unshipped'
            AND o.closed_at is null
            AND os.variants_id = " . $value['variants_id'];
            $count_sum2 = array_column(Db::query($sql2), 'count');
            $count2 = $count_sum2[0] == null ? 0 : (int)$count_sum2[0];

            $finall_count = $count + $count1 + $count2;
            //通过variants_id 更新对应的 pre_sale
            $return[] = table('skuinventory')->where(['variants_id' => $value['variants_id']])->update(['pre_sale' => $finall_count, 'updatetime' => time()]);
        }
        return success('更新成功', $return);
    }


    //重新计算sku数量
    public function   sum_sku_count()
    {
        $return = array();
        $where[] = ['pre_sale', '>', 0];
        $skuinventory_data_array =  table('skuinventory')->order(['updatetime' => 'asc'])->where($where)->limit(100)->select()->toarray();
        foreach ($skuinventory_data_array as $v) {
            $skuinventory_data =  table('skuinventory')->where(['sku' => $v['sku']])->select()->toarray();
            $count = 0;
            foreach ($skuinventory_data as  $join_data) {
                $count += (int)$join_data['pre_sale'] * (int)$join_data['sku_num'];
            }
            $sku_name = isset($skuinventory_data[0]) ? $skuinventory_data[0]['sku'] : '';
            $brand = isset($skuinventory_data[0]) ? $skuinventory_data[0]['brand'] : '';
            if (!empty($sku_name) && !empty($brand)) {
                //查找sku中的记录
                $sumskucount = table('sumskucount')->where(['sku' => $sku_name])->find();
                if (!empty($sumskucount)) {
                    table('sumskucount')->where(['sku' => $sku_name])->update(
                        [
                            'pre_sale' => $count,
                            'usable' => $sumskucount['sum'] - $count,
                            'updatetime' => time(),
                        ]
                    );
                } else {
                    table('sumskucount')->insert(
                        [
                            'pre_sale' => $count,
                            'brand' => $brand,
                            'sku' => $v['sku'],
                            'product_id' => $v['product_id'],
                            'variants_id' => $v['variants_id']
                        ]
                    );
                }
            }
        }


        return success('更新成功', $return);
    }
}
